package controle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.ParseException;

import javax.swing.JOptionPane;

import abstraction.Evaluation;
import presentation.EvalDialog;

import abstraction.Cours;

/** controleur qui ajoute une évaluation
 * 
 * @author PICOSSON
 *
 */
public class ControlJButtonSaveEval implements ActionListener {

	private Cours modele;
	private EvalDialog parent;
	private boolean creation;

	
	public ControlJButtonSaveEval(EvalDialog parent, Cours modele, boolean creation) {
		this.modele = modele;
		this.parent = parent;
		this.creation=creation;
	}
	
	
	public void actionPerformed(ActionEvent arg0) {
		Evaluation eval = null;
		if(creation)
			try {
				eval = new Evaluation(parent.getNomEval() ,modele.getModuleCourant() ,parent.getDateEval(), parent.getModeEval());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		else
			try {
				eval = new Evaluation(parent.getId_evaluation(),parent.getNomEval() ,modele.getModuleCourant() ,parent.getDateEval(), parent.getModeEval());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		try {
			if(eval.getNom().length() < 1)
				throw new Exception("Il n'y a pas de nom d'évaluation");
			
			if(!this.parent.getDateEval().matches("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$"))
				throw new Exception("La date est invalide");

			if(creation && this.modele.findEvaluation(eval.getId_module(), eval.getNom()) != null)
				throw new Exception("L'évaluation existe déjà");
			
			modele.saveEvaluation(eval, creation);
			parent.setVisible(false);
			} catch (Exception e1) {
			JOptionPane.showMessageDialog(parent, "On ne peut pas! " + e1.getMessage(), "Erreur!",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	}

